package kk;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
	public int add(Comment c) {
		String sql = "insert into `comments`(cnid,ccontent,cdate,cip,cauthor)values(?,?,?,?,?)";
		return DBUtil.executeUpdate(sql, c.getCnid(), c.getCcontent(),
				c.getCdate(), c.getCip(), c.getCauthor());
	}

	public List<Comment> findComments(Long newsid) {
		String sql = "select * from `comments` where cnid=?";
		PreparedStatement ps = null;
		Connection con = DBUtil.getConnection();
		List<Comment> datas = new ArrayList();
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql);
			ps.setObject(1, newsid);
			rs = ps.executeQuery();
			while (rs.next()) {
				Comment st = new Comment();
				st.setCid(rs.getLong("cid"));
				st.setCnid(rs.getLong("cnid"));
				st.setCcontent(rs.getString("ccontent"));
				st.setCdate(rs.getString("cdate"));
				st.setCip(rs.getString("cip"));
				st.setCauthor(rs.getString("cauthor"));
				datas.add(st);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, con);
		}
		return datas;
	}
	
	public Comment findComment(Long cid) {
		String sql = "select * from `comments` where cid=?";
		PreparedStatement ps = null;
		Connection con = DBUtil.getConnection();
		ResultSet rs = null;
		Comment st=null;
		try {
			ps = con.prepareStatement(sql);
			ps.setObject(1, cid);
			rs = ps.executeQuery();
			while (rs.next()) {
				st = new Comment();
				st.setCnid(rs.getLong("cnid"));
				st.setCcontent(rs.getString("ccontent"));
				st.setCdate(rs.getString("cdate"));
				st.setCip(rs.getString("cip"));
				st.setCauthor(rs.getString("cauthor"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, con);
		}
		return st;
	}
	
	public List<Comment> findallComments() {
		String sql = "select * from `comments`";
		PreparedStatement ps = null;
		Connection con = DBUtil.getConnection();
		List<Comment> datas = new ArrayList();
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Comment st = new Comment();
				st.setCnid(rs.getLong("cnid"));
				st.setCcontent(rs.getString("ccontent"));
				st.setCdate(rs.getString("cdate"));
				st.setCip(rs.getString("cip"));
				st.setCauthor(rs.getString("cauthor"));
				datas.add(st);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, con);
		}
		return datas;
	}
	public int del(Long id) {
		String sql = "delete from `comments` where cid=?";
		return DBUtil.executeUpdate(sql, id);
	}
}
